import React from 'react'
import CustomBreadcrumb from '../../components/CustomBreadcrumb/index'
import Avatar from '../../components/img/index'
import PicturesWall from '../../components/img/uploads'
import AvatarTable from '../../components/img/tableImg'
import {setPrice,setData} from '../../utils/Session'
import {Table, Button, Input, Modal, Form, Row, Col, Select, InputNumber, message, Popconfirm,Cascader, BackTop, Icon, Pagination} from 'antd';
import {addShop, getShop, delShop, getShopDetail,editSubmit,deleteAttrKey,deleteAttrVal,deleteTableVal,getCate,sendData} from "../../api/shop";
import ShopPrice from './shopPrice'
import Ueditor from '../../components/Ueditor'
import { values } from 'mobx'
const {TextArea} = Input;
const InputGroup = Input.Group;
const {Option} = Select;

class Shop extends React.Component {

    state = {
        editId:'',
        options:[],
        page: 1,
        size: 10,
        selectedRowKeys: [], // Check here to configure the default column
        loading: false,
        visible: false,
        priceId: '',
        sonSelect:[],
        types: [
            {
              id: 1,
              disabled: false,
              son: []
            }],
        typeValue: [],
        addTable: [],
        details: '',
        visiblePrice: false,
        images: [],
        visiblePriceDetail: false,
        commodity_image_thum: '',
        priceDetail: [],
        data: [],
        form: {},
        types_default: '',
        commodityData: '',
        ids:[],
        idTables:[],
        idTablesDel:[],
        delete_attr_key:[],
        update_val:[],
        update_key:[],
        delete_attr_val:[],
        total: 0,
        current: 0
    };
    showModal = () => {
        this.setState({
            visible: true,
        });
    };

    /**
     * 删除数据
     */
    _delShop(id) {
        delShop(id).then((res) => {
            if (res.code < 400) {
                this._getShop()
                message.success('删除成功！')
            } else {
                message.error('删除失败！')
            }
        })
    }

    /**
     * 获取商品列表数据
     */
    _getShop() {
        let data = {
            page: this.state.page,
            size: this.state.size
        }
        getShop(data).then((res) => {
            if (res.code < 400) {
                this.setState({
                    data: res.data.data,
                    total: res.data.total
                })
            }
        })
    }

    /**
     * 获取提交需要的规格分类
     * @param e
     */
    _getShopType() {
        let types = this.state.types
        // console.log(222)
        // console.log(types)
        const shopTypes = []
        for (let index in types) {
            if (types[index].son.length > 0) {
                for (let index2 in types[index].son) {
                    if(!types[index].web_type) {
                        var typeItem = {
                            son_id: types[index].son[index2].id,
                            name: types[index].son[index2].val.replace(/(^\s*)|(\s*$)/g, ""),
                            list: []
                        }
                    } else {
                        var typeItem = {
                            son_id: types[index].son[index2].id,
                            name: types[index].son[index2].val.replace(/(^\s*)|(\s*$)/g, ""),
                            list: [],
                            web_type:1
                        }
                    }
//                     console.log(11113)
// console.log(types[index].son[index2].inputs)
                    if (types[index].son[index2].inputs) {
                        for (let index3 in types[index].son[index2].inputs) {
                            let list = ''
                            if(!types[index].son[index2].inputs[index3].web_type){
                                let val = types[index].son[index2].inputs[index3].val
                                 list = {
                                    attr_value:val.replace(/(^\s*)|(\s*$)/g, "") ,
                                    symbol: types[index].son[index2].inputs[index3].id,
                                }
                            } else {
                                let val = types[index].son[index2].inputs[index3].val
                                 list = {
                                    attr_value:val.replace(/(^\s*)|(\s*$)/g, "") ,
                                    symbol: types[index].son[index2].inputs[index3].id,
                                    web_type:1
                                }
                            }
                            typeItem.list.push(list)
                        }
                    }
                    shopTypes.push(typeItem)
                }
            }

        }
        return shopTypes
    }

    /**
     * 获取表格数据
     * @param e
     * @returns {Promise<void>}
     */
    _getTables() {
        let addTable = this.state.addTable
        for (let index in addTable) {
            let son = addTable[index].son
            let sons = []
            for (let index2 in son) {
                sons.push(son[index2].shopId)
            }
            addTable[index].sons = Array.from(new Set(sons))
        }
        for (let index in addTable) {
            let son = addTable[index].son
            let sons = addTable[index].sons
            let sonList = []
            for (let index2 in sons) {
               for (let index3 in son) {
                   if (typeof (son[index3]) == 'object' && sons[index2] == son[index3].shopId ) {
                       sonList.push(son[index3])
                       break;
                   }
               }
            }
            addTable[index].son = sonList
        }
        for (let index in addTable) {
            if (addTable[index].son.length > 0) {
                let name = []
                let ids = []
                for (let index2 in addTable[index].son) {
                    let val = addTable[index].son[index2].val
                    name.push(val.replace(/(^\s*)|(\s*$)/g, ""))
                    ids.push(addTable[index].son[index2].id)
                }
                if (name.length > 0) {
                    addTable[index].sku_name = name.join(" ")
                }
                if (ids.length > 0) {
                    addTable[index].symbol_path = ids.join(",")
                }
            }
        }
        return addTable
    }

    /**
     * 修改数据
     */
    _editSubmit(data){
        editSubmit(data).then((res)=>{
            if(res.code <400) {
                message.success('修改成功!')
                this._getShop()
                this.setState({
                    visible: false
                })
                window.location.reload()
            }
        })
    }
    /**
     * 提交数据
     * @param e
     * @returns {Promise<void>}
     */
    handleOk = async (e) => {
        let shopTypes = await this._getShopType()
        let tables = await this._getTables()
        // console.log(111)
        // console.log(tables)
        const form = []
        form.attribute_data = JSON.stringify(shopTypes)
        form.mall_classify_id = this.state.mall_classify_id
        let mall_classify_ids = this.state.mall_classify_ids
        if(typeof mall_classify_ids === 'object'){
            form.mall_classify_ids = mall_classify_ids.join(",")
        } else {
            form.mall_classify_ids = mall_classify_ids
        }
        form.sku_data = JSON.stringify(tables)
        const details = this.state.form.details
        const commodity_image_thum = this.state.commodity_image_thum
        const images = this.state.images
        form.images = JSON.stringify(images)
        form.commodity_image_thum = commodity_image_thum
        form.details = details
        this.props.form.validateFields((err, values) => {
            if (err === null) {
                const formData = Object.assign({}, values, form)
                if (formData.sku_data.length === 2) {
                    message.warning("请添加商品属性信息")
                    return false
                }
                let editId = this.state.editId
              if (editId) {
                  let editFormData = formData
                  editFormData.id =editId
                  editFormData.delete_sku_data = this.state.idTablesDel
                  editFormData.delete_attr_key = this.state.delete_attr_key
                  editFormData.delete_attr_val = this.state.delete_attr_val
                  editFormData.delete_price_data = this.state.delete_price_data
                  editFormData.details = this.state.details
                    this._editSubmit(editFormData)
              } else {
                  formData.attribute_data = JSON.parse(formData.attribute_data)
                  formData.sku_data = JSON.parse(formData.sku_data)
                  for(let index in formData.attribute_data) {
                      if(!formData.attribute_data[index].web_type) {
                          formData.attribute_data[index].web_type = 1
                      }
                  }
                  for(let index in formData.sku_data) {
                      if(!formData.sku_data[index].web_type) {
                          formData.sku_data[index].web_type =1
                      }
                  }
                  formData.attribute_data = JSON.stringify(formData.attribute_data)
                  formData.sku_data = JSON.stringify(formData.sku_data)
                  formData.details = this.state.details
                  this._addShop(formData)
              }
            }
        })
    };

    handleCancel = e => {
        this.setState({
            visible: false,
            types: [
                {
                    id: 1,
                    disabled: false,
                    son: []
                }],
            addTable: [],
            details: '',
            images: [],
            commodity_image_thum: '',
            priceDetail: []
        });
    };

    // 获取输入框的值，传递给后台
    getInputValue=()=>{
      let firstInput = document.querySelectorAll('input')[0].value;
      let min_price = document.getElementById('minValue').value;
      let max_price = document.getElementById('maxValue').value;
      let data = {
        keywords: firstInput,
        min: min_price,
        max: max_price
      }
      sendData(data).then((res) => {
        this.setState({
          data: res.data.data
        })
        if(res.data.data.length === 0){
          this.setState({
            total: -1
          })
          let jump = document.getElementById('jumpVessel');
          jump.style.display = 'none';
        }else{
          this.setState({
            total: res.data.data.total
          })
        }
      })
    }

    start = () => {
        this.setState({loading: true});
        setTimeout(() => {
            this.setState({
                selectedRowKeys: [],
                loading: false,
            });
        }, 1000);
    };

    onSelectChange = selectedRowKeys => {
        this.setState({selectedRowKeys});
    };

    componentDidMount() {
        this._getShop()
        this._getCate()
    }

    /**
     * 获取分类
     */
    _getCate(){
        getCate().then((res) => {
            if(res.code < 400) {
                this.setState({
                    options:res.data
                })
            }
        })
    }
    /***
     * 删除分类
     */
    _deleteAttrKey(id,editId){
       return  deleteAttrKey(id,editId).then((res) => {
            return res
        })
    }

    /**
     * 删除分类
     */
    _deleteAttrVal(id){
        let editId = this.state.editId
        return deleteAttrVal(id,editId).then((res) => {
            return res
        })
    }
    /**
     * 删除表格
     */
    _deleteTableVal(id){
        let editId = this.state.editId
        return deleteTableVal(id,editId).then((res) => {
            return res
        })
    }
    /**
     * 添加分类
     * @returns {*}
     */
    typeAdd = () => {
        const leg = this.state.types
        let le = leg.length
        le++
        const letype = {
            id: le,
            val:'',
            disabled: false,
            web_type:1,
            son: []
        }
        const types = [...leg, letype]
        this.setState({
            types
        })
    }

    /**
     * 添加子集
     */
    /**
     * 生成不重复的id
     * @param e
     */
    addId() {
        let types = this.state.types
        const ids = []
        for (let index in types) {
            for (let index1 in types[index].son) {
                if (types[index].son[index1]) {
                    var inputs = types[index].son[index1].inputs
                    if (inputs.length > 0) {
                        for (let index2 in inputs) {
                            ids.push(inputs[index2].id)
                        }
                    }
                }
            }
        }
        if (ids.length === 0) {
            return 1
        } else {
            ids.sort((a, b) =>
                b - a
            )
            return (ids[0] + 1)
        }
    }
    typeSonAdd = (e) => {
        if (e) {
            let idAdd = this.addId()
            const id = e.target.id
            const typesData = this.state.types
            for (let index in typesData) {
                let son = typesData[index].son
                if (typesData[index].id === parseInt(id)) {
                    for (let key in son) {
                        if (son[key].id === parseInt(id)) {
                            var val = {
                                perId: id,
                                id: idAdd,
                                web_type:1
                            }
                            typesData[index].son[key].inputs.push(val)
                        }
                    }
                }
            }
            // console.log(3333)
            // console.log(typesData)
            this.setState({
                types: [...typesData]
            })
        }
    }
    /**
     * 删除
     */
    typeSonColse = async (val) => {
        const id = parseInt(val)
        let res = await this._deleteAttrVal(id)
        if (res.code < 400) {
            let types = this.state.types
            let delete_attr_val = this.state.delete_attr_val
            for (let index in types) {
                for (let key in types[index].son) {
                    const inputs = types[index].son[key].inputs
                    for (let index1 in inputs) {
                        if (parseInt(inputs[index1].id) === id) {
                            delete_attr_val.push(id)
                            inputs.splice(index1, 1)
                        }
                    }
                    if (inputs.length === 0) {
                        types[index].son.splice(key, 1)
                    }
                }
            }
            this.setState({
                types
            })
        }

    }
    /**
     *
     * 取消
     * @returns {*}
     */
    typeColse = async (e) => {
        const id = e.target.id
        let editId = this.state.editId
        // console.log(id)
        let del = await this._deleteAttrKey(id,editId)
        // console.log(del)

        if (del.code < 400) {
            let types = this.state.types
            var typesData = []
            for (let index in types) {
                if (types[index].id !== parseInt(id)) {
                    typesData.push(types[index])
                }
            }
            let delete_attr_key = this.state.delete_attr_key
            delete_attr_key.push(id)
            this.setState({
                types: typesData,
                delete_attr_key
            })
        }else {
            message.warning(del.message)
        }


    }
    onBlur = (e) => {
        const val = e.target.value
        const id = e.target.id
        let idAdd = this.addId()
        const types = this.state.types
        if (val) {
            const typeValues = {
                id: parseInt(id),
                val,
                inputs: [
                    {
                        perId: id,
                        id: idAdd
                    }
                ],
                web_type:1
            }
            var tj = 0
            for (let index in types) {
                let son = types[index].son
                for (let index in son) {
                    if ((son[index].val === val) && son[index].id !== parseInt(id)) {
                        tj++
                        // console.log('重复添加')
                    }
                }
                if (parseInt(types[index].id) === parseInt(id) && tj === 0) {
                    const son = types[index].son
                    let num = 0
                    for (let key in son) {
                        if (parseInt(son[key].id) !== parseInt(id) && son[key].val.toString() !== val.toString()) {
                            num++
                        }
                        if (parseInt(son[key].id) === parseInt(id)) {
                            if(!types[index].web_type){
                                let update_key  = this.state.update_key
                                update_key .push(id)
                                this.setState({
                                    update_key
                                })
                            }
                            types[index].son[key].val = val
                            types[index].val = val
                        }
                    }
                    if (son.length === 0 || num > 0) {
                        types[index].son.push(typeValues)
                        types[index].val = val
                    }
                }
            }
            // console.log(types)
            this.setState({
                types
            })
        }

    }
    /**
     * 获取动态添加的input值
     */
    inputValues = (e) => {
        let types = this.state.types
        let id = e.target.id
        let val = e.target.value
        let son = []
        for (let index in types) {
            for (let key in types[index].son) {
                const inputs = types[index].son[key].inputs
                for (let index1 in inputs) {
                    if (parseInt(inputs[index1].id) === parseInt(id)) {
                        inputs[index1].val = val
                        if(!inputs[index1].web_type) {
                            let update_val = this.state.update_val
                            if(!update_val.includes(id)){
                                update_val.push(id)
                            }
                        }
                    }
                    let vals = {
                        shopId:parseInt(inputs[index1].perId),
                        val:inputs[index1].val,
                        id:inputs[index1].id,
                    }
                    son.push(vals)
                }
            }
        }
        // for (let index in addTable) {
        //     addTable[index].son = son
        // }
        this.setState({
            types,
            sonSelect:son
        })
    }
    /**
     * 添加表格
     */
    AddTable = () => {
        let sonSelect = this.state.sonSelect
        const addTables = this.state.addTable
        let id = 1
        for (let index in addTables) {
            addTables[index].active = false
            id = addTables[index].id
            id++
        }
        var val = {
            id,
            active: true,
            son: [],
            stock: '',
            bar_code: '',
            original_price: '',
            sku_name: '',
            commodity_image_thum:'',
            image: '',
            symbol_path: '',
            prices: [],
            tableType:[],
            web_type:1
        }
        addTables.push(val)
        // console.log(addTables)
        this.setState({
            addTable: addTables
        })
    }
    /**修改库存
     *
     */
    setStock = (e) => {
        let addTables = this.state.addTable
        for (let index in addTables) {
            if (parseInt(addTables[index].id) === parseInt(e.target.id)) {
                addTables[index].stock = e.target.value
            }
        }
        let id = e.target.id
        let idTables = this.state.idTables
        if(!idTables.includes(id)) {
            idTables.push(id)
        }
        this.setState({
            addTable: addTables
        })
    }
    /**
     * 修改价格
     */
    setPrice = (e) => {
        let addTables = this.state.addTable
        for (let index in addTables) {
            if (parseInt(addTables[index].id) === parseInt(e.target.id)) {
                addTables[index].original_price = e.target.value
            }
        }
        let id = e.target.id
        let idTables = this.state.idTables
        if(!idTables.includes(id)) {
            idTables.push(id)
        }
        this.setState({
            addTable: addTables
        })
    }
    /**
     * 修改code
     *
     */
    setCode = (e) => {
        let addTables = this.state.addTable
        for (let index in addTables) {
            if (parseInt(addTables[index].id) === parseInt(e.target.id)) {
                addTables[index].bar_code = e.target.value
            }
        }
        let id = e.target.id
        let idTables = this.state.idTables
        if(!idTables.includes(id)) {
            idTables.push(id)
        }
        this.setState({
            addTable: addTables
        })
    }
    /***
     * 删除表格数据
     */
    delTable = async (e) => {
        let id = e.target.id
        let addTables = this.state.addTable
        let res = await this._deleteTableVal(id)
        // console.log(res)
        if(res.code <400){
            // console.log("sss")
            for (let index in addTables) {
                if (addTables[index].id === parseInt(id)) {
                    addTables.splice(index, 1)
                }
            }
            let idTablesDel = this.state.idTablesDel
            if(!idTablesDel.includes(id)) {
                idTablesDel.push(id)
            }
            this.setState({
                addTable: addTables
            })
        }

    }

    /**
     * 下拉框值改动
     */
    handleTypeChange = (val,id,pid) =>{
        let type = val.split(",")
        let idTables = this.state.idTables
        if (!idTables.includes(pid)){
            idTables.push(pid)
        }
        let addTable = this.state.addTable
        for (let index in addTable) {
            let num = 0
            if (addTable[index].id === pid) {
                for (let index2 in addTable[index].son) {
                    if (addTable[index].son[index2].shopId === parseInt(id)) {
                        num ++
                        addTable[index].son[index2].id = parseInt(type[0])
                        addTable[index].son[index2].val = type[1]
                    }
                }
                if (num === 0) {
                    let tableType = {
                        shopId:id,
                        id: parseInt(type[0]),
                        val:type[1]
                    }
                    addTable[index].son.push(tableType)
                }
            }

        }
        // console.log(addTable)
       this.setState({
           addTable
       })
    }
    /**
     * 获取下拉框
     * @param value
     */
    handleProvinceChange = value => {
        const inputId = parseInt(value)
        let types = this.state.types
        let sonId = ''
        let val = ''
        let id = ''
        for (let index in types) {
            let son = types[index].son
            for (let index2 in son) {
                let inputs = son[index2].inputs
                for (let idnex3 in inputs) {
                    if (parseInt(inputs[idnex3].id) === inputId) {
                        sonId = son[index2].id
                        val = inputs[idnex3].val
                        id = inputs[idnex3].id
                    }
                }
            }
        }
        let addTables = this.state.addTable
        if (addTables.length > 0) {
            for (let index in addTables) {
                if (addTables[index].active) {
                    var son = {
                        sonId,
                        val,
                        id
                    }
                    let num = 0
                    for (let index2 in addTables[index].son) {
                        if (addTables[index].son[index2].sonId === sonId) {
                            num++
                            addTables[index].son[index2].val = val
                            addTables[index].son[index2].id = id
                        }
                    }
                    if (num === 0) {
                        addTables[index].son.push(son)
                    }
                }
            }
        }
        this.setState({
            addTable: addTables
        })
    }

    /**
     * 提交数据到接口
     */
    _addShop(data) {
        addShop(data).then(res => {
            if (res.code < 400 && res.code!==0) {
                message.success('添加成功!')
                this.setState({
                    visible: false,
                    types: [
                        {
                            id: 1,
                            disabled: false,
                            son: []
                        }],
                    addTable: [],
                    details: '',
                    images: [],
                    commodity_image_thum: '',
                    priceDetail: []
                })
                this.props.form.resetFields()
                // this.forceUpdate();
                window.location.reload()
                this._getShop()
            }
        })
    }

    /**
     * 文档框的值
     */
    content = (e) => {
        this.setState({
            details: e
        })
    }
    /**
     * 设置价格
     */
    setPrices = (e) => {
        let id = e.target.id
        let addTables = this.state.addTable

        let price = ''
        for (let index in addTables) {
            if(addTables[index].id === parseInt(id)) {
                price = addTables[index].prices
            }
        }
        this.setState({
            visiblePrice: true,
            priceId: id,
            priceDetail: price
        })
    }
    getPageValue = () => {
      console.log('回车')
      let intValue = document.getElementById('sousuo').value;
      var data = {
        page: intValue,
        size: 10
      }
     
      getShop(data).then((res) => {
        if (res.code < 400) {
            this.setState({
                data: res.data.data
            })
        }else if(res.data.data.length === 0){
          let ulDemo = document.querySelectorAll('ul')[3];
            // console.log(ulDemo);
            ulDemo.style.display = 'none';
        }
      })
    }

    
    // 页面跳转逻辑
    changePage = (page) => {
      this.setState({
        current: page,
      }, () => {
        var data = {
          page: this.state.current,
          size: 10
        }
        getShop(data).then((res) => {
          if (res.code < 400) {
              this.setState({
                  data: res.data.data
              })
          }
        })
      })
    }
    onPressEnter=()=>{
      let enterInput = document.getElementById('onPressEnter').value;
      const data = {
        page: enterInput,
        size: 10
      }
      getShop(data).then((res) => {
        if (res.code < 400) {
            this.setState({
                data: res.data.data,
                current: res.data.current_page
            })
        }
      })
    }
    /*
    *关闭价格
    */
     handlePriceOk(){
        this.setState({
            visiblePrice: false
        })
        // 获取添加价格数据
    // console.log('id')
         let idData = this.refs.getPriceList.getIds()
         let ids = this.state.ids
         for (let index in  idData.ids) {
             if (!ids.includes(idData.ids[index])) {
                 ids.push(idData.ids[index])
             }
         }
         for (let index in  ids) {
             if (idData.delIds.includes(ids[index])) {
                 ids.splice(index,1)
             }
         }
         let delete_price_data = idData.delete_price_data
        // console.log(ids)
        let tables =  this._getTables()
        // 获取添加的表格的当前id
        let priceId = this.state.priceId
        this.setState({
            ids,
            delete_price_data
        })
        message.success('设置成功！')
    }
    /**
     * 取消价格
     */
    handlePriceCancel = () => {
        this.setState({
            visiblePrice: false
        })
    }
    /**
     * 商品图片列表
     */
    images = (e) => {
        this.props.form.setFieldsValue({
            images: e
        })
        this.setState({
            images: e
        })
    }
    /**
     * 获取单张图片
     */
    getImg = (e) => {
        this.props.form.setFieldsValue({
            commodity_image_thum: e
        })
        this.setState({
            commodity_image_thum: e
        })
    }
    getTableImg = (imgUrl, id) => {
        let addTables = this.state.addTable
        for (let index in addTables) {
            if (parseInt(addTables[index].id) === parseInt(id)) {
                addTables[index].image = imgUrl
            }
        }
        this.setState({
            addTable: addTables
        })
    }
    TableDetails = (e) => {
        let id = e.target.id
        let addTables = this.state.addTable
        let price = ''
        for (let index in addTables) {
            if (parseInt(addTables[index].id) === parseInt(id)) {
                price = addTables[index].prices
            }
        }
        this.setState({
            visiblePriceDetail: true,
            priceDetail: price
        })
    }
    /**详情
     */
    pricesDetailOk = async () => {
        let pricesIds = this.refs.priceDetail.getPriceIds()
        this.setState({
            visiblePrice: false
        })
        // 获取表格数据
        let tables = await this._getTables()

        // 获取添加的表格的当前id
        let priceId = this.state.priceId
        for (let index in tables) {
            if (parseInt(tables[index].id) === parseInt(priceId)) {
                for (let index2 in pricesIds) {
                    tables[index].prices.splice(pricesIds[index2], 1)
                }
            }
        }
        this.setState({
            addTable: tables,
            visiblePriceDetail: false
        })
    }

    /**
     * 获取详细
     * @private
     */
    _getShopDetail(id) {
        return getShopDetail(id).then((res) => {
            if (res.code < 400 && res.code !==0 ) {
                return res.data
            }
        })
    }

    /**
     * 修改商品
     */
    async edit(e) {
        this.setState({
            title:'修改商品',
            typeValue: [],
            addTable: [],
            details: '',
            visiblePrice: false,
            visiblePriceDetail: false,
            priceDetail: [],
            types_default: '',
            commodityData: '',
            ids:[],
            idTables:[],
            idTablesDel:[],
            delete_attr_key:[],
            update_val:[],
            update_key:[],
            delete_attr_val:[]
        })
        let id = e.target.id
        let shopDetail = await this._getShopDetail(id)
        let data = []
        let attribute = shopDetail.attribute
        let sons = []
        if (attribute) {
            for (let index in attribute) {
                let id = attribute[index].son_id
                let none = {
                    id,
                    val: attribute[index].attr_name,
                    son: []
                }
                data.push(none)
            }
            for (let index in attribute) {
                for (let index2 in data) {
                    if (parseInt(data[index2].id) === parseInt(attribute[index].son_id)) {
                        let vals = []
                        if (attribute[index].vals) {
                            for (let index3 in attribute[index].vals) {
                                let val = {
                                    id: attribute[index].vals[index3].symbol,
                                    perId: attribute[index].son_id,
                                    val: attribute[index].vals[index3].attr_value
                                }
                                let valSon = {
                                    id:attribute[index].vals[index3].symbol,
                                    shopId:attribute[index].son_id,
                                    val: attribute[index].vals[index3].attr_value
                                }
                                vals.push(val)
                                sons.push(valSon)
                            }
                        }
                        let val = {
                            id: attribute[index].son_id,
                            val: attribute[index].attr_name,
                            inputs: vals
                        }
                        data[index2].son.push(val)
                    }
                }
            }
        }
        let images= []
        for (let index in shopDetail.images) {
            images.push(shopDetail.images[index].commodity_image)
        }
        shopDetail.images = images
        this.props.form.setFieldsValue({
            commodity_name: shopDetail.commodity_name,
            brief_introduction: shopDetail.brief_introduction,
            total_stock: shopDetail.total_stock,
            images: shopDetail.images,
            unit: shopDetail.unit,
            market_price: shopDetail.market_price,
            commodity_image_thum: shopDetail.commodity_image_thum,
            types: data,
            // max_price:shopDetail.max_price,
            mall_classify_id:shopDetail.mall_classify_id,
            // min_price:shopDetail.min_price
        })
        if (shopDetail) {
            // console.log(121212)
            let commodity_sku = shopDetail.commodity_sku
            // console.log(commodity_sku)
            // console.log(121212)
            for (let index in commodity_sku) {
                commodity_sku[index].son = JSON.parse(commodity_sku[index].sku_son)
            }
            setPrice(commodity_sku)
            setData(data)
            let mall_classify_ids = shopDetail.mall_classify_ids
            shopDetail.mall_classify_ids = mall_classify_ids.split(",")
            for (let index in shopDetail.mall_classify_ids) {
                shopDetail.mall_classify_ids[index] = parseInt(shopDetail.mall_classify_ids[index])
            }
            this.setState(
                {
                    visible: true,
                    form: shopDetail,
                    details:shopDetail.details,
                    types: data,
                    addTable:commodity_sku,
                    sonSelect:sons,
                    editId:id,
                    commodity_image_thum: shopDetail.commodity_image_thum,
                    images: shopDetail.images,
                    mall_classify_ids:shopDetail.mall_classify_ids,
                    mall_classify_id:shopDetail.mall_classify_id
                }

            )
        }
    }
    add = () => {
        this.setState({
            visible: true,
            editId:'',
            title:'添加商品',
            mall_classify_id:'',
            mall_classify_ids:'',
            typeValue: [],
            addTable: [],
            details: '',
            visiblePrice: false,
            images: [],
            visiblePriceDetail: false,
            commodity_image_thum: '',
            priceDetail: [],
            form: {},
            types_default: '',
            commodityData: '',
            ids:[],
            idTables:[],
            idTablesDel:[],
            delete_attr_key:[],
            update_val:[],
            update_key:[],
            delete_attr_val:[]
        })
        this.props.form.resetFields()

    }
    CateonChange = (val) =>{
        let ids = val
        if(val.length > 0) {
            this.props.form.setFieldsValue({
                mall_classify_id:ids[ids.length-1]
            })
            this.setState({
                mall_classify_id:ids[ids.length-1],
                mall_classify_ids:ids.join(",")
            })
        }
    }
    
    textNone = () =>{
      let firstInput = document.querySelectorAll('input')[0].value;
      if(firstInput === ''){
        const data = {
          page:1,
          size:10
      }
      getShop(data).then((res) => {
        if (res.code < 400) {
            this.setState({
                data: res.data.data,
                total: res.data.total,
                current_page: res.data.current_page
            })
            let jump = document.getElementById('jumpVessel');
            jump.style.display = 'block';
          }
        })
      }
    }
    
    render() {
        const columns = [
            {
                title: '序号',
                width: 100,
                align: 'center',
                render: (text, record, index) => {
                    return (index + 1)
                }
            },
            {
                title: '商品名称',
                dataIndex: 'commodity_name',
                width: 200,
                align: 'center'
            },
            {
                title: '市场价格',
                dataIndex: 'market_price',
                width: 160,
                align: 'center',
                render: (text,record,index)=>{
                  return `${text} 元`
                }
            },
            {
                title: '价格区间',
                dataIndex: 'min_price_max_price',
                width: 160,
                align: 'center',
                render: (text,record,index) => {
                  return `${record.min_price} ~ ${record.max_price} 元`
                }
            },
            {
                title: '图片',
                dataIndex: 'commodity_image_thum',
                width: 160,
                align: 'center',
                render: (text, record) => {
                    return <img width="50" height="50" src={text}/>
                }
            },
            {
                title: '总库存',
                dataIndex: 'total_stock',
                width: 140,
                align: 'center'
            },
            {
                title: '操作',
                key: 'action',
                align: 'center',
                width: 280,
                render: (text, record) => (
                    <span>
                     <Button style={{marginRight: 10}} id={record.id} onClick={
                         this.edit.bind(this)
                     }>修改</Button>
                    <Popconfirm
                        title="你确认要删除吗?"
                        onConfirm={() => {
                            this._delShop(record.id)
                        }}
                        okText="确定"
                        cancelText="取消"
                    >
                    <Button type="danger" style={{marginRight: 10}}>删除</Button>
                </Popconfirm>
                 <Button style={{marginRight: 10}} onClick={() => {
                     this.props.history.push('/shopDetail/' + record.id)
                 }}>详情</Button>
             </span>
                ),
            },
        ];
        const {loading, selectedRowKeys} = this.state;
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };
        const hasSelected = selectedRowKeys.length > 0;
        const {getFieldDecorator} = this.props.form;
        return (
            <div>
                <CustomBreadcrumb arr={['商品']}/>
                <div>
                    <InputGroup compact style={{ marginBottom: '16px' }}>
                      <Button type="primary" disabled>删除</Button>
                      <Input placeholder="请输入商品名" onChange={this.textNone} style={{ width: 130, borderRight: '1px solid rgb(217,217,217)', borderTopRightRadius: '4px', borderBottomRightRadius: '4px' }}></Input>
                      <span style={{ padding: '4px 11px 4px 74px' }}>请输入价格:</span>
                      <Input placeholder="最小值" style={{ width: 100, borderRight: '1px solid rgb(217,217,217)'}} min={1} max={9999} id="minValue"/>
                      <span style={{ padding: '4px 8px' }}>~</span>
                      <Input placeholder="最大值" style={{ width: 100 }} min={1} max={9999} id="maxValue"/>
                      <Button type="primary" shape="circle" icon="search" onClick={() => this.getInputValue()} />
                      <Button type="primary" style={{ float: "right", marginRight:'10px', borderTopLeftRadius: '4px',borderBottomLeftRadius: '4px' }} onClick={() => this.add()}>添加商品</Button>
                    </InputGroup>
                </div>
                <Modal
                    title={this.state.title}
                    width={1400}
                    visible={this.state.visible}
                    onOk={this.handleOk}
                    destroyOnClose={true}
                    onCancel={this.handleCancel}
                >
                    <Form onSubmit={this.handleSubmit}>
                        <Row>
                            <Col span={10}>
                                <Form.Item label="商品名称">
                                    {getFieldDecorator('commodity_name', {
                                        rules: [
                                            {
                                                required: true,
                                                message: '请填写商品名称!',
                                            },
                                        ],
                                    })(
                                        <Row>
                                            <Col span={18}>
                                              <Input defaultValue={this.state.form.commodity_name} 
                                                     placeholder="请填写商品名称"/>
                                            </Col>
                                        </Row>
                                    )}
                                </Form.Item>
                            </Col>
                            <Col span={10}>
                                <Form.Item label="市场价格">
                                    {getFieldDecorator('market_price', {
                                        rules: [
                                            {
                                                required: true,
                                                message: '请输入价格!',
                                            },
                                        ],
                                    })(
                                        <Row>
                                            <Col span={18}>
                                              <Input defaultValue={this.state.form.market_price}
                                                     placeholder="请填写商品名称"/>
                                            </Col>
                                        </Row>)}
                                </Form.Item>
                            </Col>
                            <Col span={10}>
                                <Form.Item label="总库存">
                                    {getFieldDecorator('total_stock', {
                                        rules: [
                                            {
                                                required: true,
                                                message: '请输入总库存!',
                                            },
                                        ],
                                    })(
                                        <Row>
                                            <Col span={18}>
                                              <Input defaultValue={this.state.form.total_stock}
                                                     placeholder="请输入总库存"/>
                                            </Col>
                                        </Row>)}
                                </Form.Item>
                            </Col>
                            <Col span={10}>
                                <Form.Item label="单位">
                                    {getFieldDecorator('unit', {
                                        rules: [
                                            {
                                                required: true,
                                                message: '请输入单位!',
                                            },
                                        ],
                                    })(
                                        <Row>
                                            <Col span={18}>
                                              <Input defaultValue={this.state.form.unit}
                                                     placeholder="请输入单位"/>
                                            </Col>
                                        </Row>)}
                                </Form.Item>
                            </Col>
                            <Col span={10}>
                                <Form.Item label="分类">
                                    {getFieldDecorator('mall_classify_id', {
                                        rules: [
                                            {
                                                required: true,
                                                message: '请选择分类!',
                                            },
                                        ],
                                    })(
                                        <Row>
                                            <Col span={18}> <Cascader defaultValue={this.state.form.mall_classify_ids} options={this.state.options} onChange={this.CateonChange} placeholder="请选择分类" />
                                            </Col>
                                        </Row>)}
                                </Form.Item>
                            </Col>
                            <Col span={10}>
                                <Form.Item label="最小价格">
                                    {getFieldDecorator('min_price', {
                                        rules: [
                                            {
                                              required: true,
                                              message: '请输入最小价格!',
                                            },
                                        ],
                                    })(
                                        <Row>
                                            <Col span={18}> 
                                              <Input defaultValue={this.state.form.min_price}
                                                     placeholder="请输入最小价格"/>
                                            </Col>
                                        </Row>)}
                                </Form.Item>
                            </Col>
                            <Col span={10}>
                                <Form.Item label="最大价格">
                                    {getFieldDecorator('max_price', {

                                    })(
                                        <Row>
                                            <Col span={18}>
                                              <Input defaultValue={this.state.form.max_price}
                                                     placeholder="填写则为最小值,填写则为区间"/>
                                            </Col>
                                        </Row>)}
                                </Form.Item>
                            </Col>
                            <Col span={20}>
                                <Form.Item label="商品图片">
                                    {getFieldDecorator('images', {
                                        rules: [
                                            {
                                                required: true,
                                                message: '请填写商品图片!',
                                            },
                                        ],
                                    })(
                                        <Row>
                                            <Col span={10}>
                                                <PicturesWall images={this.images} imagesList={this.state.form.images}/>
                                            </Col>
                                        </Row>
                                    )}
                                </Form.Item>
                            </Col>
                            <Col span={6}>
                                <Form.Item label="封面缩略图">
                                    {getFieldDecorator('commodity_image_thum', {
                                        rules: [
                                            {
                                              required: true,
                                              message: '请上传封面缩略图!',
                                            },
                                        ],
                                    })(
                                        <Row>
                                            <Col span={10}>
                                                <Avatar getImg={this.getImg} commodity_image_thum={this.state.commodity_image_thum}/>
                                            </Col>
                                        </Row>)}
                                </Form.Item>
                            </Col>
                            <Col span={18}>
                                <Form.Item label="商品简介">
                                    {getFieldDecorator('brief_introduction', {
                                        rules: [
                                            {
                                              required: true,
                                              message: '请输入商品简介!',
                                            },
                                        ],
                                    })(
                                        <Row>
                                            <Col span={20}> <TextArea defaultValue={this.state.form.brief_introduction}
                                                                      rows={4}/>
                                            </Col>
                                        </Row>)}
                                </Form.Item>
                            </Col>
                            <Col span={20}>
                                <Form.Item label="设置分类">
                                    {getFieldDecorator('types', {
                                        rules: [
                                            {
                                              required: true,
                                              message: '请设置分类!',
                                            },
                                        ],
                                    })(
                                        <Row>
                                            {
                                                this.state.types.map((item) => {
                                                    return (
                                                        <Row key={item.id}>
                                                            <Col span={4} style={{marginRight: 10}}>
                                                              <Input
                                                                placeholder="请设置分类"
                                                                defaultValue={item.val}
                                                                id={item.id} onBlur={(e) => this.onBlur(e)}/>
                                                            </Col>
                                                            {
                                                               <Col span={2}>
                                                                  <Button type="danger" id={item.id}
                                                                          onClick={(e) => {
                                                                            this.typeColse(e)
                                                                          }}>
                                                                    删除
                                                                  </Button>
                                                                </Col>
                                                            }
                                                        </Row>
                                                    )
                                                })
                                            }
                                            <Col span={2}>
                                              <Button type="primary" onClick={() => {
                                                this.typeAdd()
                                            }}>
                                                添加
                                              </Button>
                                            </Col>
                                        </Row>)}
                                </Form.Item>
                            </Col>
                            {
                                this.state.types.map((items) => {
                                    return items.son.map((item) => {
                                        return <Col key={item.id} span={20}>
                                            <Form.Item label={item.val}>
                                                <Row>
                                                    {
                                                        item.inputs.map((key) => {
                                                            return (
                                                                <Row key={key.id}>
                                                                    <Col span={4} style={{marginRight: 10}}>
                                                                      <Input
                                                                        id={key.id}
                                                                        defaultValue={key.val}
                                                                        onBlur={(e) => this.inputValues(e)}/>
                                                                    </Col>
                                                                    {
                                                                     <Col span={2}>
                                                                       <Button type="danger"
                                                                          onClick={() => {
                                                                          this.typeSonColse(key.id)
                                                                          }}>
                                                                            删除
                                                                        </Button>
                                                                      </Col>
                                                                    }
                                                                </Row>
                                                            )
                                                        })
                                                    }
                                                    <Col span={2}>
                                                      <Button type="primary" id={item.id}
                                                              onClick={(e) => {
                                                              this.typeSonAdd(e)
                                                      }}>
                                                        添加
                                                      </Button>
                                                    </Col>
                                                </Row>
                                            </Form.Item>
                                        </Col>
                                    })
                                })
                            }
                            {
                                this.state.types[0].son.length > 0 ? <Col span={24}>
                                    {
                                        this.state.types.map((items) => {
                                            return (<Col span={2} key={items.id} style={{
                                                textAlign: 'center',
                                                height: '40px',
                                                lineHeight: '40px'
                                            }}>
                                                {items.val}
                                            </Col>)

                                        })
                                    }

                                    <Col span={2} style={{textAlign: 'center', height: '40px', lineHeight: '40px'}}>
                                        库存
                                    </Col>
                                    <Col span={2} style={{textAlign: 'center', height: '40px', lineHeight: '40px'}}>
                                        价格
                                    </Col>
                                    <Col span={3} style={{
                                        textAlign: 'center',
                                        height: '40px',
                                        lineHeight: '40px',
                                        marginLeft: '10px'
                                    }}>
                                        商品条形码
                                    </Col>
                                    <Col span={3} style={{textAlign: 'center', height: '40px', lineHeight: '40px'}}>
                                        图片
                                    </Col>
                                    <Col span={3} style={{textAlign: 'center', height: '40px', lineHeight: '40px'}}>
                                        <Button type="primary"
                                                onClick={(e) => {
                                                    this.AddTable(e)
                                                }}>添加</Button>
                                    </Col>
                                </Col> : ''
                            }

                            {
                                this.state.addTable.map((item, index) => {
                                    return (
                                        <Col span={24} key={index} style={{
                                            borderTop: 'solid 1px rgba(0, 0, 0, 0.15)',
                                            height: '50px',
                                            lineHeight: '50px'
                                        }}>
                                            {
                                                this.state.types.map((items, index) => {
                                                    let val = ''
                                                    items.son.map((itemData)=>{
                                                        itemData.inputs.map((itemDataSon)=>{
                                                            item.son.map((itemSon)=>{
                                                                if(itemDataSon.id === itemSon.id) {
                                                                    val =itemDataSon.val
                                                                }
                                                            })
                                                        })
                                                    })

                                                    return (<Col span={2} key={index} style={{
                                                        textAlign: 'center',
                                                        height: '40px',
                                                        lineHeight: '40px',
                                                        paddingLeft: '10px',
                                                        paddingRight: '10px'
                                                    }}>
                                                        <Select defaultValue={val} onChange={(val)=>{this.handleTypeChange(val,items.id,item.id)}} key={items.id} style={{ width: 100 }}>
                                                        {items.son.map((itemData)=>{
                                                            return  itemData.inputs.map((itemSon)=>{
                                                                return (<Option key={itemSon.id} value={itemSon.id+','+itemSon.val}>{itemSon.val}</Option>)
                                                            })
                                                        })
                                                        }
                                                    </Select>

                                                    </Col>)
                                                })
                                            }
                                            <Col span={2} style={{
                                                textAlign: 'center',
                                                height: '40px',
                                                lineHeight: '40px',
                                                paddingLeft: '10px',
                                                paddingRight: '10px'
                                            }}>
                                                <Input id={item.id}
                                                       defaultValue={item.stock}
                                                       onBlur={(e) => {
                                                           this.setStock(e)
                                                       }} placeholder="请输入库存"/>
                                            </Col>
                                            <Col span={2} style={{
                                                textAlign: 'center',
                                                height: '40px',
                                                lineHeight: '40px',
                                                paddingLeft: '10px',
                                                paddingRight: '10px'
                                            }}>
                                                <Input
                                                    defaultValue={item.original_price}
                                                    id={item.id} onBlur={(e) => {
                                                    this.setPrice(e)
                                                }} placeholder="请输入价格"/>
                                            </Col>
                                            <Col span={3} style={{
                                                textAlign: 'center',
                                                height: '40px',
                                                lineHeight: '40px',
                                                marginLeft: '20px'
                                            }}>

                                                <Input
                                                    defaultValue={item.bar_code}
                                                    id={item.id} onBlur={(e) => {
                                                    this.setCode(e)
                                                }} placeholder="请输入条形码"/>
                                            </Col>
                                            <Col span={3}
                                                 style={{
                                                     textAlign: 'center',
                                                     height: '40px',
                                                     lineHeight: '40px',
                                                     paddingLeft: '50px'
                                                 }}>

                                                <AvatarTable getImg={this.getTableImg} commodity_image_thum={item.commodity_image_thum} ref="getTableImg" id={item.id}/>
                                            </Col>
                                            <Col span={6}
                                                 style={{textAlign: 'center', height: '40px', lineHeight: '40px'}}>
                                                <Button id={item.id} type="primary"
                                                        onClick={(e) => {
                                                            this.setPrices(e)
                                                        }}>设置价格</Button>
                                                <Button type="danger" id={item.id}
                                                        onClick={(e) => {
                                                            this.delTable(e)
                                                        }}>删除</Button>
                                            </Col>
                                        </Col>
                                    )
                                })
                            }
                            <Col span={24} style={{borderTop: '1px solid rgba(0, 0, 0, 0.15)'}}>
                                <Form.Item label="商品详情">
                                    <Row>
                                        <Col>
                                            <Ueditor content={this.content.bind(this)}
                                                     value={this.state.details}>
                                            </Ueditor>
                                        </Col>
                                    </Row>
                                </Form.Item>
                            </Col>
                        </Row>
                    </Form>
                </Modal>
                {/*
               设置价格
                */}
                <Modal
                    title="设置价格(商品起始数量必须为1)"
                    width={800}
                    visible={this.state.visiblePrice}
                    onOk={this.handlePriceOk.bind(this)}
                    destroyOnClose={true}
                    onCancel={this.handlePriceCancel}
                >
                    <ShopPrice ref="getPriceList" priceList={this.state.priceDetail}></ShopPrice>
                </Modal>

                <Table rowSelection={rowSelection} rowKey="id" columns={columns} dataSource={this.state.data}  pagination={{ total: this.state.total,onChange: this.changePage, current: this.state.current }} />
                
                <span id="jumpVessel" style={{ fontSize: '14px', color: 'rgb(37,37,37)', float:'right', margin: '0px 18px 20px 0px' }}>
                    前往第&nbsp;&nbsp;<Input id="onPressEnter" onPressEnter={this.onPressEnter} style={{ width: '32px', height: '32px', padding: '4px', textAlign: 'center' }}></Input>&nbsp;&nbsp;页
                </span>
            </div>
        );
    }
}

const ShopFrom = Form.create()(Shop);
export default ShopFrom
